package com.training.java.redbox.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.DAOException;
import com.training.java.redbox.domain.Inventory;
import com.training.java.redbox.domain.InventoryDAO;
import com.training.java.redbox.domain.InventoryDAOJDBCImpl;
import com.training.java.redbox.domain.Orders;
import com.training.java.redbox.domain.OrdersDAO;
import com.training.java.redbox.domain.OrdersDAOJDBCImpl;

/**
 * Servlet implementation class OrderServlet
 */
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		List<Long> cart = (List<Long>)session.getAttribute("cart");
		Customer customer = (Customer)session.getAttribute("Customer");
		Orders order = null;
		//Inventory inventory = null;
		session.setAttribute("Orders", order);
		InventoryDAO invdao = new InventoryDAOJDBCImpl();
		OrdersDAO dao = new OrdersDAOJDBCImpl();
		try
		{
			
			long orderNum = dao.getOrderumber();
			for (long id : cart)
				{
				
				Inventory inventory = invdao.findByPrimaryKey(id);
				invdao.updateInventory(inventory);
				order = new Orders(orderNum,customer.getCustomerId(),id,"rented");
				dao.createOrders(order);
				
				}
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	}
		request.setAttribute("Orders", order);
		RequestDispatcher rd = request.getRequestDispatcher("/Order.jsp");
		rd.forward(request, response);
		
	
	}	

}
